import util from '@/utils/util.js';
import {
	getLogo
} from '@/api/api.js';

import {
	login,
	sendMsg,
	userLogin,
	updateUserInfo
} from '@/api/user.js';
let isFirst = true;
let app = getApp();
export default {
	name: 'authorize',
	data() {
		return {
			cloneIner: null,
			loading: false,
			errorSum: 0,
			errorNum: 3,
			logo_url: getApp().globalData.logo_url,


			phone: '',
			code: '',
			content: '发送验证码',
			totalTime: 30,
			canClick: true,
			is_weixin: util.is_weixin()
		}
	},
	props: {
		// 是否展示
		iShidden: {
			type: Boolean,
			value: true,
		},
		//是否自动登录
		isAuto: {
			type: Boolean,
			value: true,
			default: true,
		},
		// 是否跳转首页
		isGoIndex: {
			type: Boolean,
			value: true,
		},
	},
	// attached() { 
	// 	console.log("attached")
	//     this.setAuthStatus();
	// },

	beforeMount() {
		console.log("beforeMount,isAuto",this.isAuto)
		//加载后半秒执行
		if(this.isAuto)
		{
			this.setAuthStatus();
		}
		
	},

	onLoad() {
		if (!that.data.userInfo) {
			let userInfo = uni.getStorageSync('usetinfo')
			that.getUserInfo(userInfo);
		}
	},
	
	methods: {
		close() {
			let pages = getCurrentPages();
			let currPage = pages[pages.length - 1];
			if (this.isGoIndex) {
				// uni.switchTab({
				// 	url: '/pages/index/index'
				// });
			} else {
				this.setData({
					iShidden: true
				});
				if (currPage && currPage.iShidden != undefined) {
					currPage.setData({
						iShidden: true
					});
				}
			}
		},
		//检测登录状态并执行自动登录
		async setAuthStatus() {
			var that = this;
			util.chekWxLogin().then(async (res) => {
				// console.log(res.isLog)
				// debugger
				// console.log(res.data.indexOf("\\\\") == -1)
				if (res.isLog) {
					// uni.showLoading({
					// 	title: '正在登录中...'
					// });
					uni.setStorageSync('app_key', res.data);
					app.globalData.token = res.data.token;
					app.globalData.seconds = res.data.seconds;
					app.globalData.isLog = true;
					that.setData({
						iShidden: false
					});
					uni.hideLoading();
					console.log("触发了onLoadFun")
					// 触发onLoadFun事件
					that.$emit('onLoadFun');

			
			
					let resData = res.data.userInfo;
					if (resData && JSON.stringify(resData) != "{}") {
						app.globalData.userInfo = resData;
						app.globalData.userInfo.avatarUrl ? '' : app.globalData.userInfo.avatarUrl = resData
							.avatarUrl;
						app.globalData.userInfo.nickName ? '' : app.globalData.userInfo.nickName = resData
							.nickName;
					}
					return resolve();
			
				} else {
			
					let pages = getCurrentPages();
					let currPage = pages[pages.length - 1];
					if (currPage && currPage.iShidden != undefined) {
						currPage.setData({
							iShidden: true
						});
					}
				 await that.changePlatform();
					
				}
			}).catch(async res => {
				console.log(err, 'changePlatform')
				 await that.changePlatform();
			})


		},
		async changePlatform() {
			let that = this;
			// #ifdef MP-WEIXIN
			that.setAuthWx();
			// #endif
			// #ifdef MP-ALIPAY
			that.setData({
				iShidden: false
			});
			await that.setAuthAlipay();
			// #endif
			// #ifdef H5
			if (that.is_weixin) {
				that.setAuthGzh();
			} else {
				// that.setAuthH5();
			}

			// #endif
		},
		setAuthWx() {
			var that = this;

			// 查看是否授权
			uni.getSetting({
				success: function(res) {
					if (res.authSetting['scope.userInfo']) {
						uni.getUserInfo({
							success: function(res) {
								// 用户已经授权过,不需要显示授权页面,所以不需要改变 isHide 的值
								// 根据自己的需求有其他操作再补充
								// 我这里实现的是在用户授权成功后，调用微信的 uni.login 接口，从而获取code
								// #ifndef MP-XHS
								
								uni.login({
									success: res => {
										// 获取到用户的 code 之后：res.code
										console.log("用户的code:" + res.code);
										// 可以传给后台，再经过解析获取用户的 openid 
										uni.httpRequest({
											url: app.serverUrl + '/login/' +
												res.authCode,
											method: 'POST',
											header: {
												'content-type': 'application/json'
											},
											dataType: 'json',
											success: (res) => {
												// 授权成功并且服务器端登录成功
												console.log(res);
												that.setData({
													userInfo: res
														.data
														.data
												});
												that.setUserInfo(res
													.data.data, true
												);
											}
										});
									}
								});
								// #endif
								
								// #ifdef MP-XHS
								xhs.login({
									success: res => {
										// 获取到用户的 code 之后：res.code
										console.log("用户的code:" + res.code);
										// 可以传给后台，再经过解析获取用户的 openid 
										uni.httpRequest({
											url: app.serverUrl + '/login/' +
												res.authCode,
											method: 'POST',
											header: {
												'content-type': 'application/json'
											},
											dataType: 'json',
											success: (res) => {
												// 授权成功并且服务器端登录成功
												console.log(res);
												that.setData({
													userInfo: res
														.data
														.data
												});
												that.setUserInfo(res
													.data.data, true
												);
											}
										});
									}
								});
								// #endif
							
							}
						});
					} else {
						// 用户没有授权
						// 改变 isHide 的值，显示授权页面
						that.setData({
							isHide: true
						});
					}
				}
			});
		},
		async setAuthAlipay() {
			var that = this;
			// debugger
			// 示例
			// try {
			// 	debugger
			// 	my.getAuthCode({
			// 		// 订单服务授权：order_service。如需同时获取用户多项授权，可在 scopes 中传入多个 scope 值。
			// 		scopes: ['order_service', 'auth_user'],
			// 		success: (res) => {
			// 			// 订单服务授权成功
			// 			console.log(res.authCode,"getAuthCode")
			// 			const authCode = res.authCode;
			// 			uni.setStorageSync('order_service_userInfo', res.authCode)
			// 			// 继续获取用户信息
						
			// 			my.getOpenUserInfo({
			// 				success: (userInfoRes) => {
			// 					const userInfo = JSON.parse(userInfoRes.response).response;
			// 					console.log('User Info:', userInfo);
			// 					that.$emit('onLoadFun');
			// 					// 将用户信息发送到后端
			// 					uni.setStorageSync('UserInfo', userInfo)
			// 				},
			// 				fail: (error) => {
			// 					console.error('获取用户信息失败', error);
			// 				}
			// 			});
			// 		},
			// 		fail: (res) => {
			// 			// 订单服务授权失败，根据自己的业务场景来进行错误处理
			// 		},
			// 	});
			// } catch (e) {
			// 	console.log(" 订单服务授权失败，根据自己的业务场景来进行错误处理")
			// }
			// #ifndef MP-XHS
			await uni.getAuthCode({
				
				scopes: ['auth_base', 'order_service', 'auth_user'],
				success: (rescode) => { //获取用户信息
					console.log(rescode, '支付宝授权')
					that.setData({
						iShidden: false
					});
					uni.getAuthUserInfo({

						success: (res) => {
							console.log(res, '支付宝用户授权')
							let userInfo = {
								avatarUrl: res.avatar,
								nickName: res.nickName,
								code: rescode.authCode
							}
							uni.setStorageSync('userInfo', userInfo)
							console.log(rescode.authCode)
							that.setData({
								userInfo: userInfo
							});
							that.setUserInfo(userInfo, true);

						},
						fail: async (res) => {
							console.log(1)
							let userInfo = {
								// avatarUrl: res.avatar,
								// nickName: res.nickName,
								code: rescode.authCode
							}
							uni.setStorageSync('userInfo', userInfo)
							console.log(rescode.authCode)
							that.setData({
								userInfo: userInfo
							});
							await that.setUserInfo(userInfo, true);
						}

					});

				},
				fail: (res) => {
					that.close();
				}

			});
			// #endif
			// #ifdef MP-XHS
			// xhs.getSetting({
			//   success(res) {
			//     if (!res.authSetting['scope.userInfo']) {
			//       xhs.authorize({
			//         scope: 'scope.userInfo',
			//         success () {
			//           // 用户已经同意小程序使用录音功能，后续调用 xhs.startRecord 接口不会弹窗询问
			//           xhs.startRecord()
			//         }
			//       })
			//     }
			//   }
			// })
			// #endif

		},
		//授权
		async setUserInfo(userInfo, isLog) {
			let that = this;
			uni.showLoading({
				title: '正在登录中...'
			});
			// debugger
			if (isLog) {
				await that.getUserInfo(userInfo);
			} else {
				// debugger
				await util.getCodeLogin(async (res) => {
					// debugger
					var userInfo = await util.wxgetUserInfo();
					userInfo.code = res.code;
					userInfo.avatarUrl = userInfo.avatarUrl || userInfo.avatar;
					await that.getUserInfo(userInfo);
					
					
				});
			}
		},
	  getUserInfo: async function(params) {
			let that = this;
			// userInfo.spread_spid = app.globalData.spid;//获取推广人ID
			// userInfo.spread_code = app.globalData.code;//获取推广人分享二维码ID
			params.appId ? '' : params.appId = app.globalData.appid;
			console.log(params, 'userLogin')
			await userLogin(params).then(res => {
				if (res.status == 200) {
					// 更新用户信息
					if (app.globalData.isLog) {
						updateUserInfo(params)
					}

					if (JSON.stringify(res.data) == "{}") {
						return uni.showToast({
							title: "登录信息获取异常",
							icon: 'none'
						})
					} else {
						// uni.setNavigationBarTitle({
						// 	title: res.data.name
						// })
						uni.$emit('updata',{appName:res.data.name})
						app.globalData.appName  = res.data.name
						app.globalData.userInfo = res.data.userInfo;
						app.globalData.userInfo.avatarUrl ? '' : app.globalData.userInfo.avatarUrl = params
							.avatarUrl;
						app.globalData.userInfo.nickName ? '' : app.globalData.userInfo.nickName = params
							.nickName;

						res.data.seconds = Math.round(new Date() / 1000) + res.data.seconds;
						app.globalData.token = res.data.token;
						app.globalData.seconds = res.data.seconds;
						app.globalData.isLog = true;
						uni.setStorageSync('app_key', JSON.stringify(res.data));

						that.setData({
							iShidden: false
						});
						// 获取登录信息 

						uni.hideLoading();
						console.log("触发了onLoadFun")
						that.$emit('onLoadFun');
					}

				} else if ((res.status == 0 || res.status == 500) && isFirst) {
					// #ifdef H5
					isFirst = false;
					// uni.removeStorageSync('app_key');
					uni.removeStorageSync('code');
					that.setAuthStatus();
					console.log('code失效')
					// #endif 	 
					uni.hideLoading();
				} else {
					uni.hideLoading();
					that.errorSum++;
					that.setData({
						errorSum: that.errorSum
					});
					if (that.errorSum >= that.errorNum) {
						util.Tips({
							title: err
						});
					} else {
						that.setUserInfo(params);
					}
					that.code = ""
				}
			}).catch(res => {
				uni.hideLoading();
				that.errorSum++;
				console.log(res, 'userLogin错误', that.errorSum)
				that.setData({
					errorSum: that.errorSum
				});
				if (that.errorSum >= that.errorNum) {
					util.Tips({
						title: err
					});
				} else {
					// #ifdef H5
					isFirst = false;
					// uni.removeStorageSync('app_key');
					uni.removeStorageSync('code');
					that.setAuthStatus();
					console.log('code失效')
					// #endif 	
					// #ifndef H5
					that.setUserInfo(params);
					// #endif 	
				}
				that.code = ""
			})

		},

		// H5登录
		setAuthH5() {
			let that = this;
			if (!that.phone) {
				uni.showToast({
					title: '请输入手机号码',
					icon: 'none'
				})
			} else if (!/^1[3456789]\d{9}$/.test(that.phone)) {
				uni.showToast({
					title: '请输入正确的手机号码',
					icon: 'none'
				})
			} else if (!that.code) {
				uni.showToast({
					title: '请输入验证码',
					icon: 'none'
				})
			} else {
				uni.showLoading({
					title: '正在登录...'
				});
				// var sId = JSON.parse(localStorage.getItem('sId')); 
				let params = {
					phone: that.phone,
					code: that.code,
					appId: app.globalData.appid,
					sId: uni.getStorageSync('sId')
				}
				that.getUserInfo(params);

			}
		},
		// 发送验证码
		sendMessage() {
			let that = this;
			if (!that.phone) {
				uni.showToast({
					title: '请输入手机号码',
					icon: 'none'
				})
			} else if (!/^1[3456789]\d{9}$/.test(that.phone)) {
				uni.showToast({
					title: '请输入正确的手机号码',
					icon: 'none'
				})
			} else {
				if (!that.canClick) return
				that.canClick = false
				that.content = that.totalTime + 's后重新发送'
				let clock = window.setInterval(() => {
					that.totalTime--
					that.content = that.totalTime + 's后重新发送'
					if (that.totalTime < 0) {
						window.clearInterval(clock)
						that.content = '发送验证码'
						that.totalTime = 10
						that.canClick = true //这里重新开启
					}
				}, 1000)
				uni.showLoading({
					title: '验证码发送中...'
				});
				sendMsg({
					phone: that.phone
				}).then(res => {
					uni.showToast({
						title: '发送成功',
						icon: 'none'
					});
					uni.hideLoading();
				});
			}

		},
		setAuthGzh() {
			var that = this;
			try {
				const code = uni.getStorageSync('code');
				console.log('code1', code);
				if (code) {
					let code2 = code.split("=")[1].split("&")[0];
					console.log('code2', code2);
					var sId = JSON.parse(localStorage.getItem('sId'));
					localStorage.removeItem('htmlLink');
					let params = {
						code: code2,
						appId: app.globalData.appid,
						sId: sId
					}
					that.getUserInfo(params);


				} else {
					// uni.showToast({title:"去授权登录"})
					let REDIRECT_URI = this.urlencode(window.location.origin + '/pages/index/login');
					let link = window.location.href;
					localStorage.setItem('htmlLink', link)
					window.location.replace(
						`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${app.globalData.appid}&redirect_uri=${REDIRECT_URI}&response_type=code&scope=snsapi_userinfo&state=1&connect_redirect=1#wechat_redirect`
					);
				}
				that.setData({
					iShidden: false
				});
			} catch (e) {

			}

		},

		urlencode(clearString) {
			var output = '';
			var x = 0;

			clearString = this.utf16to8(clearString.toString());
			var regex = /(^[a-zA-Z0-9-_.]*)/;

			while (x < clearString.length) {
				var match = regex.exec(clearString.substr(x));
				if (match != null && match.length > 1 && match[1] != '') {
					output += match[1];
					x += match[1].length;
				} else {
					if (clearString[x] == ' ') {
						output += '+';
					} else {
						var charCode = clearString.charCodeAt(x);
						var hexVal = charCode.toString(16);
						output += '%' + (hexVal.length < 2 ? '0' : '') + hexVal.toUpperCase();
					}
					x++;
				}
			}
			return output;
		},
		utf16to8(str) {
			var out, i, len, c;
			out = "";
			len = str.length;
			for (i = 0; i < len; i++) {
				c = str.charCodeAt(i);
				if ((c >= 0x0001) && (c <= 0x007F)) {
					out += str.charAt(i);
				} else if (c > 0x07FF) {
					out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
					out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
					out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
				} else {
					out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
					out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
				}
			}
			return out;
		},

	},

}